/**
 * 高阶组件 => 高阶函数
 * 1. 定义
 * const withCount = (BaseComponent)=>{
 *   class Wrapper extends Component {
 *      state = {}
 *      method = ()=>{}
 *      render() {
 *        return <BaseComponent {...this.state} />
 *      }
 *   }
 *   return Wrapper
 * }
 * 2. 使用
 * const HocCom = withCount(函数组件/类组件)
 */
import { Component } from 'react'

// 需求：复用count和count+1状态逻辑
/**
 *
 * @param {*} BaseComponent 被包裹/增强组件
 */
const withCount = (BaseComponent) => {
  class Wrapper extends Component {
    // 定义：复用的状态逻辑
    state = {
      count: 0,
      test: 'count',
    }
    add = () => {
      this.setState({
        count: this.state.count + 1,
      })
    }

    render() {
      console.log(this.props)
      // 注意：把复用的状态逻辑传给被增强的组件
      return (
        <BaseComponent
          {...this.props}
          count={this.state.count}
          add={this.add}
        />
      )
    }
  }
  console.log(BaseComponent.name)
  Wrapper.displayName = `With${BaseComponent.name}`
  return Wrapper
}

// 使用withCount
const Fn1 = ({ count, add, abc }) => {
  return (
    <div>
      <ul>
        <li>{count}</li>
        <li>{abc}</li>
        <li onClick={add}>add</li>
      </ul>
    </div>
  )
}
const Hoc1 = withCount(Fn1)

const Fn2 = ({ count, add }) => {
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={add}>add</button>
    </div>
  )
}
const Hoc2 = withCount(Fn2)
class Com extends Component {
  render() {
    return <div>{this.props.count}</div>
  }
}
const Hoc3 = withCount(Com)

// 测试
function App() {
  return (
    <div>
      <h1>高阶组件定义和使用</h1>
      <hr />
      {/* Hoc1?=> */}
      <Hoc1 abc={123} />
      <hr />
      <Hoc2 />
      <hr />
      <Hoc3 />
    </div>
  )
}

export default App
